package com.atguigu.flink.window;

import com.atguigu.flink.function.MyUtil;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * Created by Smexy on 2023/2/27
 *
 *  处理时间: 参考计算机的物理时钟
 *
 *
 *  process: 特点是灵活。
 *            是全量聚合，一个窗口在触发运算(关闭)时，只调用一次。
 */
public class Demo4_TimeKeyedWindow
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   //5s的滚动窗口  每5s算一次，一次算过去5s中到达的数据 举例: [0,10) , [10,20)
                   .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                   .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>()
                   {
                       @Override
                       public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                           List<WaterSensor> waterSensors = MyUtil.parseToList(elements);

                           TimeWindow timeWindow = context.window();
                           out.collect(MyUtil.parseTimeWindow(timeWindow) + ":"+key + ":"+waterSensors.toString());
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    }
}
